package com.david.bluetooth;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

import com.david.bluetooth.ble.BleClientActivity;
import com.david.bluetooth.ble.BleServerActivity;
import com.david.bluetooth.ble.musicctr.MusicBleClientActivity;
import com.david.bluetooth.ble.musicctr.MusicBleServerActivity;
import com.david.bluetooth.ble.musicctr.MusicClientActivity;
import com.david.bluetooth.ble.musicctr.MusicServerActivity;
import com.david.bluetooth.bt.BtClientActivity;
import com.david.bluetooth.bt.BtServerActivity;

public class MainActivity extends AppCompatActivity {
    //动态申请通知权限
    private ActivityResultLauncher requestPermissionLauncher = registerForActivityResult(
            new ActivityResultContracts.RequestPermission(),
            (ActivityResultCallback) result -> Log.e("permission", "result is " + result.toString())
    );
    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        if (Build.VERSION.SDK_INT >= 33) {
//        检测通知权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
                    == PackageManager.PERMISSION_GRANTED) {
                // Permission granted
            } else {
                // Permission not granted
                requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
            }
//        }


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //跳转app的系统通知设置
//        if (!NotificationManagerCompat.from(this).areNotificationsEnabled()) {
//            Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
//            intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
//            startActivity(intent);
//        }


        // 检查是否支持BLE蓝牙
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            APP.toast("本机不支持低功耗蓝牙！", 0);
            finish();
            return;
        }

        // Android 6.0动态请求权限
        String[] permissions;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE
                    , Manifest.permission.READ_EXTERNAL_STORAGE
                    , Manifest.permission.ACCESS_COARSE_LOCATION
                    , Manifest.permission.BLUETOOTH_ADVERTISE
                    , Manifest.permission.BLUETOOTH_CONNECT
                    , Manifest.permission.BLUETOOTH_SCAN
            };
        } else {
            permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE
                    , Manifest.permission.READ_EXTERNAL_STORAGE
                    , Manifest.permission.ACCESS_COARSE_LOCATION
            };
        }
        boolean allPermissionGrant = true;
        for (String str : permissions) {
            if (checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(permissions, 111);
                allPermissionGrant = false;
            }
        }
        if (allPermissionGrant) {
            setBluetoothEnable();
        }
    }

    private void setBluetoothEnable() {
        // 检查蓝牙开关
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter == null) {
            APP.toast("本机没有找到蓝牙硬件或驱动！", 0);
            finish();
            return;
        } else {
            if (!adapter.isEnabled()) {
                //直接开启蓝牙
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "请先开启蓝牙权限", Toast.LENGTH_LONG).show();
                    return;
                }
                adapter.enable();
                //跳转到设置界面
                startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 112);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for (int item: grantResults) {
            if (item != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "请先开启权限", Toast.LENGTH_LONG).show();
                return;
            }
        }
        setBluetoothEnable();
    }

    public void btClient(View view) {
        startActivity(new Intent(this, BtClientActivity.class));
    }

    public void btServer(View view) {
        startActivity(new Intent(this, BtServerActivity.class));
    }

    public void bleClient(View view) {
        startActivity(new Intent(this, BleClientActivity.class));
    }
    public void bleMusicClient(View view) {
//        startActivity(new Intent(this, MusicBleClientActivity.class));
        startActivity(new Intent(this, MusicClientActivity.class));
    }

    public void bleMusicServer(View view) {
//        startActivity(new Intent(this, MusicBleServerActivity.class));
        startActivity(new Intent(this, MusicServerActivity.class));
    }

    public void bleServer(View view) {
        startActivity(new Intent(this, BleServerActivity.class));
    }
}
